package com.lcache.common.redis;

import com.lcache.common.config.ConfigReader;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.support.ConnectionPoolSupport;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.time.Duration;

/**
 * @program: LIM
 * @description: redis管理类
 * @author: Alex Wu
 * @createDate: 2025-04-15 10:02
 **/
public class RedisClientManager {
    private static GenericObjectPool<StatefulRedisConnection<String, String>> pool;

    static {
        ConfigReader configReader = ConfigReader.getInstance();

        String host = configReader.getOrDefault("redis.host", String.class, "");
        int port = configReader.getOrDefault("redis.port", Integer.class,0);
        String password = configReader.getOrDefault("redis.password", String.class,"");
        int database = configReader.getOrDefault("redis.database", Integer.class,1);
        int timeoutSeconds = configReader.getOrDefault("redis.timeoutSeconds", Integer.class,0);

        // 构建 RedisURI
        RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
                .withDatabase(database)
                .withTimeout(Duration.ofSeconds(timeoutSeconds));

        if (password != null && !password.isEmpty()) {
            builder.withPassword(password.toCharArray());
        }

        RedisClient redisClient = RedisClient.create(builder.build());

        // 读取连接池配置
        int maxTotal = configReader.getOrDefault("redis.pool.maxTotal", Integer.class, 10);
        int maxIdle = configReader.getOrDefault("redis.pool.maxIdle", Integer.class, 5);
        int minIdle = configReader.getOrDefault("redis.pool.minIdle", Integer.class, 1);
        int maxWaitMillis = configReader.getOrDefault("redis.pool.maxWaitMillis", Integer.class, 2000);

        GenericObjectPoolConfig<StatefulRedisConnection<String, String>> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWait(Duration.ofMillis(maxWaitMillis));

        pool = ConnectionPoolSupport.createGenericObjectPool(redisClient::connect, poolConfig);
    }

    public static StatefulRedisConnection<String, String> getConnection() throws Exception {
        return pool.borrowObject();
    }

    public static void returnConnection(StatefulRedisConnection<String, String> connection) {
        pool.returnObject(connection);
    }

}
